package controllers.utils;

import java.io.Serializable;
import java.sql.*;
import javax.annotation.Resource;
import javax.el.ELContext;
import javax.enterprise.context.ApplicationScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.sql.DataSource;

@ApplicationScoped
@Named("databaseHjelper")
public class DatabaseHjelper implements Serializable {
    @Resource(name = "jdbc/sysprosjresource")
    private DataSource dataSource;

    // TODO! Bytt til ContextLookupHjelper
    // Henter ut den ene ApplicationScopede b0nna :).
    public static DatabaseHjelper hent() {
        final ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        return (DatabaseHjelper) FacesContext.getCurrentInstance().getApplication()
                           .getELResolver().getValue(elContext, null, "databaseHjelper");
    }

    public Connection finnForbindelse() throws SQLException {
        return dataSource.getConnection();
    }

    public static void lukk(ResultSet res) {
        try {
            if (res != null) {
                res.close();
            }
        } catch (SQLException e) {
            skrivMelding(e, "lukkResSet()");
        }
    }

    public static void lukk(Statement stm) {
        try {
            if (stm != null) {
                stm.close();
            }
        } catch (SQLException e) {
            skrivMelding(e, "lukkSetning()");
        }
    }

    public static void lukk(Connection forbindelse) {
        try {
            if (forbindelse != null) {
                forbindelse.close();
            }
        } catch (SQLException e) {
            skrivMelding(e, "lukkForbindelse()");
        }
    }

    public static void skrivMelding(Exception e, String melding) {
        System.err.println("*** Feil oppstått: " + melding + ". ***");
        e.printStackTrace(System.err);
    }
}
